package com.highcom.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.highcom.common.RedisConstant;
import com.highcom.config.RedisConfig;
import com.highcom.entity.PageResult;
import com.highcom.entity.QueryPageBean;
import com.highcom.mapper.*;
import com.highcom.model.*;
import com.highcom.service.SetMealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version 1.0
 * @Author YangJiaQuan_hrbnu
 * @Date 2024/8/1 17:19
 */
@Service
public class SetMealServiceImpl implements SetMealService {
    private static JedisPool jedisPool;
    @Autowired
    private RedisConfig redisConfig;
    @PostConstruct
    public void init(){
        jedisPool = redisConfig.redisPoolFactory();
    }

    @Resource
    private TSetmealMapper tSetmealMapper;

    @Resource
    private TSetmealCheckgroupMapper tSetmealCheckgroupMapper;

    @Resource
    private TCheckgroupMapper tCheckgroupMapper;

    @Resource
    private TCheckgroupCheckitemMapper tCheckgroupCheckitemMapper;

    @Resource
    private TCheckitemMapper tCheckitemMapper;

    private static String  outPutPath="D:\\JavaDateBase\\NEW_JAVADATEBASE\\Highcom_DateBase\\springboot-mybatis-master1\\src\\main\\resources\\static\\pages\\mobile";

    @Resource
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Override
    public void add(TSetmeal tSetmeal, Integer[] checkgroupIds) {
        tSetmealMapper.insertSelective(tSetmeal);
        // 将图片名称存储到redis中进行比较，删除七牛云服务器中未存入到数据库中的图片，实现“清除垃圾图片”需求
        String img = tSetmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,img);
        Integer id = tSetmeal.getId();

        for (Integer checkgroupId : checkgroupIds) {
            TSetmealCheckgroupKey tSetmealCheckgroupKey = new TSetmealCheckgroupKey();
            tSetmealCheckgroupKey.setSetmealId(id);
            tSetmealCheckgroupKey.setCheckgroupId(checkgroupId);
            tSetmealCheckgroupMapper.insertSelective(tSetmealCheckgroupKey);
        }
        generateMobileStaticHtml();
    }

    public void generateMobileStaticHtml(){
        List<TSetmeal> all = this.findAll();
        generateMobileSetmealListHtml(all);
        generateMobileDetailHtml(all);
    }

    public void generateMobileSetmealListHtml(List<TSetmeal> setmealList){
        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("setmealList",setmealList);
        this.generateHtml("mobile_setmeal.ftl","m_setmeal.html",dataMap);

    }
    public void generateMobileDetailHtml(List<TSetmeal> setmealList){
        for (TSetmeal tSetmeal : setmealList) {
            HashMap<Object, Object> dataMap = new HashMap<>();
            dataMap.put("setmeal",findById(tSetmeal.getId()));
            this.generateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+tSetmeal.getId()+".html",dataMap);
        }
    }
    public void generateHtml(String templateName, String htmlPageName, Map map){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        configuration.setClassicCompatible(true);
        Writer out = null;
        try {
            Template template =  configuration.getTemplate(templateName);
            File dockFile = new File(outPutPath+"/"+htmlPageName);

            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dockFile)));

            template.process(map,out);
            out.close();

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage,pageSize);
        Page<Setmeal> pages = tSetmealMapper.findPage(queryString);
        return new PageResult(pages.getTotal(),pages.getResult());
    }

    @Override
    public Setmeal findById(Integer id) {
        return tSetmealMapper.findById(id);
    }

    @Override
    public List<Integer> findCheckGroupBySetmealId(Integer id) {
        return tSetmealMapper.findCheckGroupBySetmealId(id);
    }

    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //根据检查组id删除中间关系表的数据（清理原有关联关系）
        tSetmealCheckgroupMapper.deleteAssociation(setmeal.getId());
        //向中间关系表插入数据建立检查组和检查项的关联关系
        setCheckGroupAndSetmeal(setmeal.getId(),checkgroupIds);
        //更新检查组的基本信息
        tSetmealMapper.edit(setmeal);
        generateMobileStaticHtml();
    }

    @Override   //  删除逻辑：删除要同时删除数据库、redis、七牛云
    public void delete(Integer id) {
        //  redis
        String img = tSetmealMapper.findById(id).getImg();
        jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_RESOURCES,img);
        jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES,img);
        System.out.println("已经删除redis中的图片:"+img);
        //  数据库
        tSetmealMapper.deleteByPrimaryKey(id);

        generateMobileStaticHtml();
    }

    @Override
    public List<TSetmeal> findAll() {
        TSetmealExample tSetmealExample = new TSetmealExample();
        return tSetmealMapper.selectByExample(tSetmealExample);
    }

    @Override   //查询逻辑：查询套餐数据后，根据关联关系表查询出检查项与检查组，集合成列表返回成Tsetmal对象
    public TSetmeal findByIdAndCheckgroupsAndCheckItems(Integer id) {
        //  1. 查询套餐对象基本信息
        TSetmeal tSetmeal = tSetmealMapper.selectByPrimaryKey(id);
        //  2. 根据关联关系表查询该套餐所有检查组
        TSetmealCheckgroupExample tSetmealCheckgroupExample = new TSetmealCheckgroupExample();
        tSetmealCheckgroupExample.createCriteria().andSetmealIdEqualTo(id);
        List<TSetmealCheckgroupKey> tSetmealCheckgroupKeys = tSetmealCheckgroupMapper.selectByExample(tSetmealCheckgroupExample);
        //  3. 根据检查组id集合循环查询所有检查组信息并封装成集合
        List<TCheckgroup> checkgroups = new ArrayList<>();
        for (TSetmealCheckgroupKey tCheckgroup : tSetmealCheckgroupKeys) {
            TCheckgroup checkgroup = tCheckgroupMapper.selectByPrimaryKey(tCheckgroup.getCheckgroupId());
            checkgroups.add(checkgroup);
        }
        //  4. 根据检查组id集合查询关联关系表获取所有关联检查项id
        for (TCheckgroup checkgroup : checkgroups) {
            List<TCheckitem> checkItems = new ArrayList<>();
            TCheckgroupCheckitemExample example = new TCheckgroupCheckitemExample();
            example.createCriteria().andCheckgroupIdEqualTo(checkgroup.getId());
            List<TCheckgroupCheckitemKey> tCheckgroupCheckitemKeys = tCheckgroupCheckitemMapper.selectByExample(example);
        //  5. 根据查询出的检查组id集合 查询检查项，并返回集合
            for (TCheckgroupCheckitemKey tCheckgroupCheckitemKey : tCheckgroupCheckitemKeys) {
                TCheckitem tCheckitem = tCheckitemMapper.selectByPrimaryKey(tCheckgroupCheckitemKey.getCheckitemId());
                checkItems.add(tCheckitem);
            }
        //  6. 开始封装
            checkgroup.setCheckItems(checkItems);
        }
        tSetmeal.setCheckgroups(checkgroups);
        return tSetmeal;
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return tSetmealMapper.findSetmealCount();
    }

    public void setCheckGroupAndSetmeal(Integer setmealId,Integer [] checkgroupIds){
        if (checkgroupIds != null && checkgroupIds.length>0){
            for (Integer checkgroupId : checkgroupIds) {
                HashMap<String, Integer> map = new HashMap<>();
                map.put("setmeal_id",setmealId);
                map.put("checkgroup_id",checkgroupId);
                tSetmealCheckgroupMapper.setCheckGroupAndSetmeal(map);
            }
        }
    }
}
